package com.example.filedemo;

import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 定义文件名
        String fileName = "data.txt";
        // 定义文字信息
        String content ="内部文件存储lhd";
        // 代码的重构
        writeContentToFile(fileName, content);

        // TODO 动态获取用户授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"},
                    1);
        }

        writeContentToExternalFile("data.out.txt","你好lhd");
    }

    private void writeContentToFile(String fileName, String content) {
        // 创建fos对象，
        FileOutputStream fos=null;
        try {
            fos = openFileOutput(fileName, MODE_PRIVATE);
            fos.write(content.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    // 将content写到 外部存储 的 file 文件中
    private void writeContentToExternalFile(String file,String content){
        // 1 获取外部存储的转态
        String externalStorageState = Environment.getExternalStorageState();
        if (!externalStorageState.equals(Environment.MEDIA_MOUNTED))
            return;
        // 2 获取外部存储的路径
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        // 获取 输出文件 对象
        Log.e(TAG, "writeContentToExternalFile: "+externalStorageDirectory );
        File fl = new File(externalStorageDirectory,file);
        if (!fl.exists()){
            try {
                fl.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 3 与普通文件一样读写
        try {
            FileOutputStream fos = new FileOutputStream(fl);
            fos.write(content.getBytes());
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}